<template>
  <ResponsiveLayout 
    layout="default" 
    :show-sidebar="false" 
    :safe-area="true"
    content-padding="20px"
  >
    <!-- 移动端导航 -->
    <MobileNavigation
      v-if="isMobile"
      :title="'健康档案'"
      :show-back="true"
      @back="$router.go(-1)"
    />

    <!-- 桌面端头部 -->
    <template #header>
      <header v-if="!isMobile" class="health-header">
        <div class="header-content">
          <div class="header-left">
            <el-button type="text" @click="$router.go(-1)">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <h1>健康档案</h1>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showAddRecord = true">
              <el-icon><Plus /></el-icon>
              添加记录
            </el-button>
          </div>
        </div>
      </header>
    </template>

    <!-- 主要内容区域 -->
    <div class="health-container" :class="{ 'mobile-layout': isMobile }">
      <!-- 健康概览卡片 -->
      <div class="health-overview">
        <div class="overview-card">
          <div class="card-header">
            <h3>健康概览</h3>
            <el-button type="text" @click="refreshHealthData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          
          <div class="health-stats">
            <div class="stat-item">
              <div class="stat-icon blood-pressure">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ healthRecord?.bloodPressure || '--/--' }}</div>
                <div class="stat-label">血压 (mmHg)</div>
                <div class="stat-time">{{ formatTime(healthRecord?.lastBloodPressureTime) }}</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon heart-rate">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ healthRecord?.heartRate || '--' }}</div>
                <div class="stat-label">心率 (bpm)</div>
                <div class="stat-time">{{ formatTime(healthRecord?.lastHeartRateTime) }}</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon weight">
                <el-icon><Scale /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ healthRecord?.weight || '--' }}</div>
                <div class="stat-label">体重 (kg)</div>
                <div class="stat-time">{{ formatTime(healthRecord?.lastWeightTime) }}</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon temperature">
                <el-icon><Thermometer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ healthRecord?.temperature || '--' }}</div>
                <div class="stat-label">体温 (°C)</div>
                <div class="stat-time">{{ formatTime(healthRecord?.lastTemperatureTime) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="basic-info-card">
        <div class="card-header">
          <h3>基本信息</h3>
          <el-button 
            v-if="!isEditingBasic" 
            type="primary" 
            @click="startEditBasic"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <div v-else class="edit-actions">
            <el-button @click="cancelEditBasic">取消</el-button>
            <el-button 
              type="primary" 
              :loading="savingBasic" 
              @click="saveBasicInfo"
            >
              保存
            </el-button>
          </div>
        </div>
        
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
          class="basic-form"
        >
          <div class="form-grid">
            <el-form-item label="身高" prop="height">
              <el-input
                v-model="basicForm.height"
                :disabled="!isEditingBasic"
                placeholder="请输入身高"
                suffix-text="cm"
              />
            </el-form-item>
            
            <el-form-item label="血型" prop="bloodType">
              <el-select
                v-model="basicForm.bloodType"
                :disabled="!isEditingBasic"
                placeholder="请选择血型"
                style="width: 100%"
              >
                <el-option label="A型" value="A" />
                <el-option label="B型" value="B" />
                <el-option label="AB型" value="AB" />
                <el-option label="O型" value="O" />
                <el-option label="未知" value="unknown" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="过敏史" prop="allergies">
              <el-input
                v-model="basicForm.allergies"
                type="textarea"
                :rows="2"
                :disabled="!isEditingBasic"
                placeholder="请输入过敏史，如无请填写'无'"
              />
            </el-form-item>
            
            <el-form-item label="慢性疾病" prop="chronicDiseases">
              <el-input
                v-model="basicForm.chronicDiseases"
                type="textarea"
                :rows="2"
                :disabled="!isEditingBasic"
                placeholder="请输入慢性疾病史，如无请填写'无'"
              />
            </el-form-item>
            
            <el-form-item label="家族病史" prop="familyHistory">
              <el-input
                v-model="basicForm.familyHistory"
                type="textarea"
                :rows="2"
                :disabled="!isEditingBasic"
                placeholder="请输入家族病史，如无请填写'无'"
              />
            </el-form-item>
            
            <el-form-item label="用药情况" prop="medications">
              <el-input
                v-model="basicForm.medications"
                type="textarea"
                :rows="2"
                :disabled="!isEditingBasic"
                placeholder="请输入当前用药情况，如无请填写'无'"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 健康记录列表 -->
      <div class="records-card">
        <div class="card-header">
          <h3>健康记录</h3>
          <div class="header-actions">
            <el-select v-model="recordFilter" placeholder="筛选类型" style="width: 120px; margin-right: 12px;">
              <el-option label="全部" value="all" />
              <el-option label="血压" value="blood_pressure" />
              <el-option label="心率" value="heart_rate" />
              <el-option label="体重" value="weight" />
              <el-option label="体温" value="temperature" />
              <el-option label="血糖" value="blood_sugar" />
              <el-option label="其他" value="other" />
            </el-select>
            <el-button type="primary" @click="showAddRecord = true">
              <el-icon><Plus /></el-icon>
              添加记录
            </el-button>
          </div>
        </div>
        
        <div class="records-list">
          <div v-if="filteredRecords.length === 0" class="empty-state">
            <el-empty description="暂无健康记录">
              <el-button type="primary" @click="showAddRecord = true">
                添加第一条记录
              </el-button>
            </el-empty>
          </div>
          
          <div v-else class="record-items">
            <div 
              v-for="record in filteredRecords" 
              :key="record.id" 
              class="record-item"
            >
              <div class="record-icon" :class="record.type">
                <el-icon v-if="record.type === 'blood_pressure'"><Monitor /></el-icon>
                <el-icon v-else-if="record.type === 'heart_rate'"><Timer /></el-icon>
                <el-icon v-else-if="record.type === 'weight'"><Scale /></el-icon>
                <el-icon v-else-if="record.type === 'temperature'"><Thermometer /></el-icon>
                <el-icon v-else-if="record.type === 'blood_sugar'"><DataAnalysis /></el-icon>
                <el-icon v-else><Document /></el-icon>
              </div>
              
              <div class="record-content">
                <div class="record-header">
                  <span class="record-type">{{ getRecordTypeName(record.type) }}</span>
                  <span class="record-time">{{ formatDateTime(record.recordTime) }}</span>
                </div>
                <div class="record-value">{{ record.value }} {{ record.unit }}</div>
                <div v-if="record.notes" class="record-notes">{{ record.notes }}</div>
              </div>
              
              <div class="record-actions">
                <el-button type="text" size="small" @click="editRecord(record)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="text" size="small" @click="deleteRecord(record.id)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑记录对话框 -->
    <el-dialog
      v-model="showAddRecord"
      :title="editingRecord ? '编辑记录' : '添加健康记录'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="recordFormRef"
        :model="recordForm"
        :rules="recordRules"
        label-width="100px"
      >
        <el-form-item label="记录类型" prop="type">
          <el-select v-model="recordForm.type" placeholder="请选择记录类型" style="width: 100%">
            <el-option label="血压" value="blood_pressure" />
            <el-option label="心率" value="heart_rate" />
            <el-option label="体重" value="weight" />
            <el-option label="体温" value="temperature" />
            <el-option label="血糖" value="blood_sugar" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="数值" prop="value">
          <el-input
            v-model="recordForm.value"
            placeholder="请输入数值"
          />
        </el-form-item>
        
        <el-form-item label="单位" prop="unit">
          <el-input
            v-model="recordForm.unit"
            placeholder="请输入单位，如：mmHg、bpm、kg等"
          />
        </el-form-item>
        
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
            v-model="recordForm.recordTime"
            type="datetime"
            placeholder="选择记录时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelAddRecord">取消</el-button>
        <el-button 
          type="primary" 
          :loading="savingRecord" 
          @click="saveRecord"
        >
          {{ editingRecord ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </ResponsiveLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useResponsive } from '../utils/responsive'
import { ElMessage, ElMessageBox } from 'element-plus'
import ResponsiveLayout from '../components/ResponsiveLayout.vue'
import MobileNavigation from '../components/MobileNavigation.vue'
import {
  ArrowLeft,
  Plus,
  Edit,
  Delete,
  Refresh,
  Monitor,
  Timer,
  Scale,
  Thermometer,
  DataAnalysis,
  Document
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const { isMobile } = useResponsive()

// 表单引用
const basicFormRef = ref()
const recordFormRef = ref()

// 编辑状态
const isEditingBasic = ref(false)
const savingBasic = ref(false)
const showAddRecord = ref(false)
const savingRecord = ref(false)
const editingRecord = ref(null)
const recordFilter = ref('all')

// 健康档案数据
const healthRecord = computed(() => userStore.healthRecord)

// 基本信息表单
const basicForm = reactive({
  height: '',
  bloodType: '',
  allergies: '',
  chronicDiseases: '',
  familyHistory: '',
  medications: ''
})

// 健康记录表单
const recordForm = reactive({
  type: '',
  value: '',
  unit: '',
  recordTime: new Date(),
  notes: ''
})

// 模拟健康记录数据
const healthRecords = ref([
  {
    id: 1,
    type: 'blood_pressure',
    value: '120/80',
    unit: 'mmHg',
    recordTime: new Date('2024-01-15 09:30:00'),
    notes: '晨起测量，状态良好'
  },
  {
    id: 2,
    type: 'heart_rate',
    value: '72',
    unit: 'bpm',
    recordTime: new Date('2024-01-15 09:35:00'),
    notes: '静息心率'
  },
  {
    id: 3,
    type: 'weight',
    value: '65.5',
    unit: 'kg',
    recordTime: new Date('2024-01-14 07:00:00'),
    notes: '空腹体重'
  }
])

// 筛选后的记录
const filteredRecords = computed(() => {
  if (recordFilter.value === 'all') {
    return healthRecords.value
  }
  return healthRecords.value.filter(record => record.type === recordFilter.value)
})

// 表单验证规则
const basicRules = {
  height: [
    { pattern: /^\d+(\.\d+)?$/, message: '请输入正确的身高数值', trigger: 'blur' }
  ]
}

const recordRules = {
  type: [
    { required: true, message: '请选择记录类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入数值', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  recordTime: [
    { required: true, message: '请选择记录时间', trigger: 'change' }
  ]
}

// 格式化时间
const formatTime = (dateString) => {
  if (!dateString) return '未记录'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取记录类型名称
const getRecordTypeName = (type) => {
  const typeMap = {
    blood_pressure: '血压',
    heart_rate: '心率',
    weight: '体重',
    temperature: '体温',
    blood_sugar: '血糖',
    other: '其他'
  }
  return typeMap[type] || type
}

// 刷新健康数据
const refreshHealthData = async () => {
  try {
    await userStore.loadHealthRecord()
    ElMessage.success('健康数据已刷新')
  } catch (error) {
    console.error('刷新健康数据失败:', error)
    ElMessage.error('刷新失败，请稍后重试')
  }
}

// 开始编辑基本信息
const startEditBasic = () => {
  isEditingBasic.value = true
  Object.assign(basicForm, {
    height: healthRecord.value?.height || '',
    bloodType: healthRecord.value?.bloodType || '',
    allergies: healthRecord.value?.allergies || '',
    chronicDiseases: healthRecord.value?.chronicDiseases || '',
    familyHistory: healthRecord.value?.familyHistory || '',
    medications: healthRecord.value?.medications || ''
  })
}

// 取消编辑基本信息
const cancelEditBasic = () => {
  isEditingBasic.value = false
  Object.assign(basicForm, {
    height: healthRecord.value?.height || '',
    bloodType: healthRecord.value?.bloodType || '',
    allergies: healthRecord.value?.allergies || '',
    chronicDiseases: healthRecord.value?.chronicDiseases || '',
    familyHistory: healthRecord.value?.familyHistory || '',
    medications: healthRecord.value?.medications || ''
  })
}

// 保存基本信息
const saveBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  try {
    const valid = await basicFormRef.value.validate()
    if (!valid) return
    
    savingBasic.value = true
    const result = await userStore.updateHealthRecord(basicForm)
    
    if (result.success) {
      ElMessage.success('基本信息更新成功')
      isEditingBasic.value = false
    } else {
      ElMessage.error(result.message || '更新失败，请稍后重试')
    }
  } catch (error) {
    console.error('更新基本信息失败:', error)
    ElMessage.error('更新失败，请稍后重试')
  } finally {
    savingBasic.value = false
  }
}

// 编辑记录
const editRecord = (record) => {
  editingRecord.value = record
  Object.assign(recordForm, {
    type: record.type,
    value: record.value,
    unit: record.unit,
    recordTime: new Date(record.recordTime),
    notes: record.notes || ''
  })
  showAddRecord.value = true
}

// 取消添加记录
const cancelAddRecord = () => {
  showAddRecord.value = false
  editingRecord.value = null
  Object.assign(recordForm, {
    type: '',
    value: '',
    unit: '',
    recordTime: new Date(),
    notes: ''
  })
}

// 保存记录
const saveRecord = async () => {
  if (!recordFormRef.value) return
  
  try {
    const valid = await recordFormRef.value.validate()
    if (!valid) return
    
    savingRecord.value = true
    
    if (editingRecord.value) {
      // 更新记录
      const index = healthRecords.value.findIndex(r => r.id === editingRecord.value.id)
      if (index !== -1) {
        healthRecords.value[index] = {
          ...editingRecord.value,
          ...recordForm,
          recordTime: recordForm.recordTime
        }
      }
      ElMessage.success('记录更新成功')
    } else {
      // 添加新记录
      const newRecord = {
        id: Date.now(),
        ...recordForm,
        recordTime: recordForm.recordTime
      }
      healthRecords.value.unshift(newRecord)
      ElMessage.success('记录添加成功')
    }
    
    cancelAddRecord()
  } catch (error) {
    console.error('保存记录失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    savingRecord.value = false
  }
}

// 删除记录
const deleteRecord = async (recordId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条健康记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = healthRecords.value.findIndex(r => r.id === recordId)
    if (index !== -1) {
      healthRecords.value.splice(index, 1)
      ElMessage.success('记录删除成功')
    }
  } catch {
    // 用户取消
  }
}

// 初始化基本信息表单
const initBasicForm = () => {
  Object.assign(basicForm, {
    height: healthRecord.value?.height || '',
    bloodType: healthRecord.value?.bloodType || '',
    allergies: healthRecord.value?.allergies || '',
    chronicDiseases: healthRecord.value?.chronicDiseases || '',
    familyHistory: healthRecord.value?.familyHistory || '',
    medications: healthRecord.value?.medications || ''
  })
}

onMounted(() => {
  initBasicForm()
  userStore.loadHealthRecord()
})
</script>

<style scoped>
.health-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.mobile-layout {
  padding: 16px;
  padding-top: 70px;
}

.health-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.health-overview {
  margin-bottom: 24px;
}

.overview-card,
.basic-info-card,
.records-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  align-items: center;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.health-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-icon.blood-pressure {
  background: linear-gradient(45deg, #e74c3c, #c0392b);
}

.stat-icon.heart-rate {
  background: linear-gradient(45deg, #e67e22, #d35400);
}

.stat-icon.weight {
  background: linear-gradient(45deg, #3498db, #2980b9);
}

.stat-icon.temperature {
  background: linear-gradient(45deg, #9b59b6, #8e44ad);
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 2px;
}

.stat-time {
  font-size: 12px;
  color: #95a5a6;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.records-list {
  max-height: 600px;
  overflow-y: auto;
}

.record-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.record-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.record-item:hover {
  background: #e9ecef;
}

.record-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.record-icon.blood_pressure {
  background: #e74c3c;
}

.record-icon.heart_rate {
  background: #e67e22;
}

.record-icon.weight {
  background: #3498db;
}

.record-icon.temperature {
  background: #9b59b6;
}

.record-icon.blood_sugar {
  background: #27ae60;
}

.record-icon.other {
  background: #95a5a6;
}

.record-content {
  flex: 1;
}

.record-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.record-type {
  font-weight: 600;
  color: #2c3e50;
}

.record-time {
  font-size: 12px;
  color: #7f8c8d;
}

.record-value {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.record-notes {
  font-size: 12px;
  color: #7f8c8d;
}

.record-actions {
  display: flex;
  gap: 4px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .health-stats {
    grid-template-columns: 1fr;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .edit-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .record-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .record-header {
    width: 100%;
  }
  
  .record-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 自定义滚动条 */
.records-list::-webkit-scrollbar {
  width: 6px;
}

.records-list::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.records-list::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.5);
  border-radius: 3px;
}

.records-list::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.7);
}
</style>